<template>
  <div class="quill-editor-wrapper">
    <QuillEditor
      ref="quillEditor"
      v-model:content="localContent"
      contentType="html"
      :options="editorOptions"
      @ready="onEditorReady"
      @update:content="onContentUpdate"
      style="height: 100%;"
    />
  </div>
</template>

<script setup>
import { ref, watch, onBeforeUnmount, onMounted } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '开始您的创作...'
  }
})

const emit = defineEmits(['update:modelValue', 'change', 'ready'])

const quillEditor = ref(null)
const localContent = ref(props.modelValue)
const isInternalUpdate = ref(false)

// Quill 编辑器配置（中文工具栏）
const editorOptions = {
  theme: 'snow',
  placeholder: props.placeholder,
  modules: {
    toolbar: {
      container: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'align': [] }],
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        ['blockquote', 'code-block'],
        [{ 'indent': '-1'}, { 'indent': '+1' }],
        ['link', 'image'],
        ['clean']
      ],
      handlers: {}
    }
  }
}

// 中文化工具栏提示
const chineseTooltips = {
  'bold': '粗体',
  'italic': '斜体',
  'underline': '下划线',
  'strike': '删除线',
  'header': '标题',
  'size': '字体大小',
  'color': '文字颜色',
  'background': '背景颜色',
  'align': '对齐方式',
  'list': '列表',
  'bullet': '无序列表',
  'ordered': '有序列表',
  'blockquote': '引用',
  'code-block': '代码块',
  'indent': '缩进',
  'link': '插入链接',
  'image': '插入图片',
  'clean': '清除格式'
}

// 设置中文提示
const setChineseTooltips = () => {
  setTimeout(() => {
    const toolbar = document.querySelector('.quill-editor-wrapper .ql-toolbar')
    if (!toolbar) return

    // 设置按钮提示
    toolbar.querySelectorAll('button').forEach(button => {
      const className = button.className
      if (className.includes('ql-bold')) button.setAttribute('title', '粗体 (Ctrl+B)')
      else if (className.includes('ql-italic')) button.setAttribute('title', '斜体 (Ctrl+I)')
      else if (className.includes('ql-underline')) button.setAttribute('title', '下划线 (Ctrl+U)')
      else if (className.includes('ql-strike')) button.setAttribute('title', '删除线')
      else if (className.includes('ql-blockquote')) button.setAttribute('title', '引用')
      else if (className.includes('ql-code-block')) button.setAttribute('title', '代码块')
      else if (className.includes('ql-list') && button.value === 'ordered') button.setAttribute('title', '有序列表')
      else if (className.includes('ql-list') && button.value === 'bullet') button.setAttribute('title', '无序列表')
      else if (className.includes('ql-indent') && button.value === '-1') button.setAttribute('title', '减少缩进')
      else if (className.includes('ql-indent') && button.value === '+1') button.setAttribute('title', '增加缩进')
      else if (className.includes('ql-link')) button.setAttribute('title', '插入链接')
      else if (className.includes('ql-image')) button.setAttribute('title', '插入图片')
      else if (className.includes('ql-clean')) button.setAttribute('title', '清除格式')
    })

    // 设置下拉菜单提示
    toolbar.querySelectorAll('.ql-picker').forEach(picker => {
      const label = picker.querySelector('.ql-picker-label')
      if (!label) return
      
      if (picker.classList.contains('ql-header')) {
        label.setAttribute('title', '标题级别')
        const options = picker.querySelectorAll('.ql-picker-item')
        options.forEach((option, index) => {
          if (index === 0) option.textContent = '正文'
          else if (index === 1) option.textContent = '标题 1'
          else if (index === 2) option.textContent = '标题 2'
          else if (index === 3) option.textContent = '标题 3'
          else if (index === 4) option.textContent = '标题 4'
          else if (index === 5) option.textContent = '标题 5'
          else if (index === 6) option.textContent = '标题 6'
        })
      } else if (picker.classList.contains('ql-size')) {
        label.setAttribute('title', '字体大小')
        const options = picker.querySelectorAll('.ql-picker-item')
        options.forEach(option => {
          const value = option.getAttribute('data-value')
          if (value === 'small') option.textContent = '小'
          else if (!value || value === 'false') option.textContent = '正常'
          else if (value === 'large') option.textContent = '大'
          else if (value === 'huge') option.textContent = '超大'
        })
      } else if (picker.classList.contains('ql-align')) {
        label.setAttribute('title', '对齐方式')
        const options = picker.querySelectorAll('.ql-picker-item')
        options.forEach(option => {
          const value = option.getAttribute('data-value')
          if (!value) option.setAttribute('title', '左对齐')
          else if (value === 'center') option.setAttribute('title', '居中')
          else if (value === 'right') option.setAttribute('title', '右对齐')
          else if (value === 'justify') option.setAttribute('title', '两端对齐')
        })
      } else if (picker.classList.contains('ql-color')) {
        label.setAttribute('title', '文字颜色')
      } else if (picker.classList.contains('ql-background')) {
        label.setAttribute('title', '背景颜色')
      }
    })
  }, 100)
}

// 监听外部传入的 modelValue 变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== localContent.value && !isInternalUpdate.value) {
    localContent.value = newValue || ''
  }
}, { immediate: true })

// 内容更新处理
const onContentUpdate = (content) => {
  isInternalUpdate.value = true
  emit('update:modelValue', content)
  emit('change', content)
  setTimeout(() => {
    isInternalUpdate.value = false
  }, 0)
}

// 编辑器就绪
const onEditorReady = (quill) => {
  setChineseTooltips()
  emit('ready', quill)
}

// 获取编辑器实例的方法
const getQuill = () => {
  return quillEditor.value?.getQuill?.()
}

// 失去焦点
const blur = () => {
  const quill = getQuill()
  if (quill) {
    quill.blur()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  const quill = getQuill()
  if (quill) {
    const length = quill.getLength()
    quill.setSelection(length, 0)
    quill.scrollIntoView()
  }
}

// 暴露方法给父组件
defineExpose({
  getQuill,
  blur,
  scrollToBottom
})

onMounted(() => {
  setChineseTooltips()
})

onBeforeUnmount(() => {
  // Quill 会自动清理
})
</script>

<style scoped>
.quill-editor-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.quill-editor-wrapper :deep(.ql-toolbar) {
  border: 1px solid #e4e7ed;
  border-bottom: none;
  background: #fafafa;
  padding: 10px;
}

.quill-editor-wrapper :deep(.ql-container) {
  border: 1px solid #e4e7ed;
  font-size: 18px;
  line-height: 2;
  flex: 1;
  overflow-y: auto;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", 
               "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.quill-editor-wrapper :deep(.ql-editor) {
  min-height: 100%;
  padding: 30px 40px;
  
}

.quill-editor-wrapper :deep(.ql-editor.ql-blank::before) {
  
  font-style: normal;
  font-size: 18px;
  left: 40px;
}

/* 段落间距 */
.quill-editor-wrapper :deep(.ql-editor p) {
  margin-bottom: 0.8em;
}

/* 标题样式 */
.quill-editor-wrapper :deep(.ql-editor h1) {
  font-size: 32px;
  font-weight: bold;
  margin: 1em 0 0.5em;
  line-height: 1.4;
}

.quill-editor-wrapper :deep(.ql-editor h2) {
  font-size: 28px;
  font-weight: bold;
  margin: 0.9em 0 0.45em;
  line-height: 1.4;
}

.quill-editor-wrapper :deep(.ql-editor h3) {
  font-size: 24px;
  font-weight: bold;
  margin: 0.8em 0 0.4em;
  line-height: 1.5;
}

.quill-editor-wrapper :deep(.ql-editor h4) {
  font-size: 20px;
  font-weight: bold;
  margin: 0.7em 0 0.35em;
  line-height: 1.5;
}

/* 引用块样式 */
.quill-editor-wrapper :deep(.ql-editor blockquote) {
  border-left: 4px solid #409eff;
  padding-left: 16px;
  margin: 1em 0;
  color: #606266;
  font-style: italic;
}

/* 代码块样式 */
.quill-editor-wrapper :deep(.ql-editor pre) {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 16px;
  margin: 1em 0;
  overflow-x: auto;
}

/* 列表样式 */
.quill-editor-wrapper :deep(.ql-editor ul),
.quill-editor-wrapper :deep(.ql-editor ol) {
  padding-left: 2em;
  margin: 1em 0;
}

.quill-editor-wrapper :deep(.ql-editor li) {
  margin-bottom: 0.5em;
}

/* 工具栏按钮样式优化 */
.quill-editor-wrapper :deep(.ql-toolbar button) {
  width: 32px;
  height: 32px;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.quill-editor-wrapper :deep(.ql-toolbar button:hover) {
  background-color: #ecf5ff;
  color: #409eff;
}

.quill-editor-wrapper :deep(.ql-toolbar button.ql-active) {
  background-color: #409eff;
  color: #fff;
}

/* 下拉选择器样式 */
.quill-editor-wrapper :deep(.ql-toolbar .ql-picker) {
  font-size: 14px;
}

.quill-editor-wrapper :deep(.ql-toolbar .ql-picker-label) {
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s;
}

.quill-editor-wrapper :deep(.ql-toolbar .ql-picker-label:hover) {
  background-color: #ecf5ff;
  color: #409eff;
}

/* 字体大小选项 */
.quill-editor-wrapper :deep(.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before) {
  content: '小' !important;
  font-size: 12px !important;
}

.quill-editor-wrapper :deep(.ql-snow .ql-picker.ql-size .ql-picker-item::before) {
  content: '正常' !important;
  font-size: 14px !important;
}

.quill-editor-wrapper :deep(.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before) {
  content: '大' !important;
  font-size: 16px !important;
}

.quill-editor-wrapper :deep(.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before) {
  content: '超大' !important;
  font-size: 18px !important;
}

/* 滚动条美化 */
.quill-editor-wrapper :deep(.ql-container)::-webkit-scrollbar {
  width: 8px;
}

.quill-editor-wrapper :deep(.ql-container)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.quill-editor-wrapper :deep(.ql-container)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.quill-editor-wrapper :deep(.ql-container)::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 黑暗模式下的柔和暗色背景 */
html.dark .quill-editor-wrapper :deep(.ql-toolbar) {
  background: #1a2332 !important;
  border-color: #414d63 !important;
}

html.dark .quill-editor-wrapper :deep(.ql-container) {
  background: #1a2332 !important;
  border-color: #414d63 !important;
}

html.dark .quill-editor-wrapper :deep(.ql-editor) {
  background: #1a2332 !important;
  color: #e4e7ed !important;
}

html.dark .quill-editor-wrapper :deep(.ql-editor.ql-blank::before) {
  color: #6c757d !important;
}

/* 工具栏按钮在黑暗模式下的样式 */
html.dark .quill-editor-wrapper :deep(.ql-toolbar button:hover) {
  background-color: rgba(255, 255, 255, 0.1) !important;
  color: #409eff !important;
}

html.dark .quill-editor-wrapper :deep(.ql-toolbar button.ql-active) {
  background-color: #409eff !important;
  color: #fff !important;
}

html.dark .quill-editor-wrapper :deep(.ql-toolbar .ql-picker-label:hover) {
  background-color: rgba(255, 255, 255, 0.1) !important;
  color: #409eff !important;
}

/* 滚动条在黑暗模式下的样式 */
html.dark .quill-editor-wrapper :deep(.ql-container)::-webkit-scrollbar-track {
  background: #1a2332 !important;
}

html.dark .quill-editor-wrapper :deep(.ql-container)::-webkit-scrollbar-thumb {
  background: #495057 !important;
}

html.dark .quill-editor-wrapper :deep(.ql-container)::-webkit-scrollbar-thumb:hover {
  background: #6c757d !important;
}
</style>

